"""
持续集成脚本
用于自动化测试和验证
"""
import os
import sys
import subprocess
import json

# 添加项目根目录到Python路径
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
sys.path.insert(0, parent_dir)

def run_command(command, description):
    """运行命令并返回结果"""
    print(f"\n正在执行: {description}")
    print(f"命令: {command}")
    
    try:
        result = subprocess.run(
            command, 
            shell=True, 
            capture_output=True, 
            text=True,
            cwd=parent_dir  # 使用项目根目录作为工作目录
        )
        
        if result.returncode == 0:
            print(f"✅ {description} - 成功")
            if result.stdout:
                print(f"输出: {result.stdout}")
            return True
        else:
            print(f"❌ {description} - 失败")
            if result.stderr:
                print(f"错误: {result.stderr}")
            return False
    except Exception as e:
        print(f"❌ {description} - 异常: {str(e)}")
        return False

def main():
    """主函数"""
    print("开始执行持续集成检查...")
    
    results = {
        'total': 0,
        'passed': 0,
        'failed': 0,
        'checks': {}
    }
    
    # 1. 代码风格检查
    results['total'] += 1
    results['checks']['code_style'] = run_command(
        "python -m flake8 app/ --max-line-length=100 --ignore=E501,W503",
        "代码风格检查"
    )
    if results['checks']['code_style']:
        results['passed'] += 1
    else:
        results['failed'] += 1
    
    # 2. 数据库结构验证
    results['total'] += 1
    results['checks']['database_structure'] = run_command(
        "python scripts/validate_database.py",
        "数据库结构验证"
    )
    if results['checks']['database_structure']:
        results['passed'] += 1
    else:
        results['failed'] += 1
    
    # 3. 单元测试
    results['total'] += 1
    results['checks']['unit_tests'] = run_command(
        "python -m pytest tests/ -v",
        "单元测试"
    )
    if results['checks']['unit_tests']:
        results['passed'] += 1
    else:
        results['failed'] += 1
    
    # 4. 应用启动测试
    results['total'] += 1
    results['checks']['app_startup'] = run_command(
        f"python -c \"import sys; sys.path.insert(0, '{parent_dir}'); from app import create_app; app = create_app('testing'); client = app.test_client(); client.get('/health')\"",
        "应用启动测试"
    )
    if results['checks']['app_startup']:
        results['passed'] += 1
    else:
        results['failed'] += 1
    
    # 输出结果
    print("\n" + "="*50)
    print("持续集成检查结果:")
    print(f"总检查项: {results['total']}")
    print(f"通过: {results['passed']}")
    print(f"失败: {results['failed']}")
    print(f"成功率: {results['passed']/results['total']*100:.1f}%")
    
    # 详细结果
    print("\n详细结果:")
    for check, result in results['checks'].items():
        status = "✅ 通过" if result else "❌ 失败"
        print(f"  {check}: {status}")
    
    # 返回适当的退出代码
    if results['failed'] > 0:
        print("\n❌ 持续集成检查失败")
        sys.exit(1)
    else:
        print("\n✅ 所有检查通过")
        sys.exit(0)

if __name__ == '__main__':
    main()